package com.web.fsc.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.web.fsc.domain.User;
import com.web.fsc.service.IUserService;

@Controller
public class UserController {
	@Autowired
	private IUserService userService;
	@Autowired
	private HttpServletRequest request;
	
	//private Logger logger=LoggerFactory.getLogger(UserController.class);
	
	@RequestMapping(value="login")
	public ModelAndView Login(ModelAndView mav,User user){
		User u=userService.Login(user.getName(),user.getPassword());
		if (u!=null){
			request.getSession().setAttribute("user", u);
			mav.addObject("user",u);
			mav.setViewName("index");
			return mav;
		}else{
			mav.setViewName("login");
		}
		return mav;
	}
	
	@SuppressWarnings("unused")
	@RequestMapping(value="register")
	public String Register(User user){
		Logger logger=LoggerFactory.getLogger(UserController.class);
		if (userService.findByName(user.getName()) != null){
			return "register";
		}
//		if (request.getParameter("identity").equals("0")){
//			user.setAdmin(false);
//		}
//		else {
//			user.setAdmin(true);
//		}
		User u=userService.Register(user);
		logger.info(String.valueOf(u.isAdmin()));
		if (u!=null)
		{
			request.getSession().setAttribute("user", u);
			return "index";
		}else
		return "register";
	}
	
	@RequestMapping(value="logout")
	public String Logout(){
		userService.Logout();
		return "index";
	}
	
	@RequestMapping(value = "listAllUser")
	@ResponseBody
	public ModelAndView listAllUser(ModelAndView mav) {
		List<User> userAllList = new ArrayList<>();
		userAllList = userService.listAll();
		mav.addObject("userAllList", userAllList);
		mav.setViewName("admin");
		return mav;
	}
	
	@RequestMapping(value = "deleteUser")
	public ModelAndView delete(Long id, ModelAndView mav) {
		if (id != null)
			userService.delete(id);
		List<User> userAllList = new ArrayList<>();
		userAllList = userService.listAll();
		mav.addObject("userAllList", userAllList);
		mav.setViewName("admin");
		return mav;
	}
}
